package com.dbq.fast;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Point;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.view.Display;
import android.view.WindowManager;

import com.dbq.fast.analysis.EventCallBack;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.util.Cache;
import com.dbq.fast.util.RudenessScreenHelper;
import com.dbq.fast.util.SpUtil;
import com.dbq.fast.util.SystemUtil;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.bugly.crashreport.CrashReport;
import com.yiba.logutils.LogUtils;
import com.yiba.logutils.save.impl.LogRecorder;
import com.yiba.logutils.utils.FileUtil;
import com.yiba.vpn.utils.Constants;
import com.yiba.vpn.utils.RxBus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by sunkai on 2017/10/24.
 */

public class App extends MultiDexApplication {

    private static Context context;
    private static App instance;
    public static Cache<String, String> cache;
    public static int SCREEN_WIDTH;


    public static App getInstance() {
        return instance;
    }

    public static Context getContext() {
        return context;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        this.context = getApplicationContext();
        instance = this;
        User.getInstance().init();
        SpUtil.init(this);
        cache = new Cache<>();
        loadLocalProxyDomain();
        //默认上传当前的国家
        YibaAnalysis.getInstance().setUserProperty(context,"country",SystemUtil.getCountry(context));

        com.yiba.logutils.utils.LogConfig.setUid("".equals(User.getInstance().getAccount())? SystemUtil.getAndroidId(this):User.getInstance().getAccount());
        new RudenessScreenHelper(this, 720).activate();

        //统计模块初始化
        YibaAnalysis.getInstance().init(context, false, 1 ,  new EventCallBack() {
            @Override
            public void event(String event) {
                RxBus.get().post(Constants.RXBUG_LOG, "event: " + event);
            }

            @Override
            public void pageInterval(String event) {
                RxBus.get().post(Constants.RXBUG_LOG, "page: " + event);
            }

            @Override
            public void active(String event) {
                RxBus.get().post(Constants.RXBUG_LOG, "active: " + event);
            }
        });
        /**
         * Facebook 统计
         */
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);
        initCrashReport();
        CrashReport.initCrashReport(getApplicationContext());
        LeakCanary.install(this);

        calculateScreenWidth();

    }

    private void calculateScreenWidth() {
        Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        Point screen = new Point();
        SCREEN_WIDTH = Math.min(screen.x, screen.y);
        display.getSize(screen);
    }

    private void initCrashReport() {
        LogUtils.getInstance()
                .setCacheSize(100 * 1024)//支持设置缓存大小，超出后清空
                .setLogDir(getApplicationContext(),
//                        FileHelper.getLogDir(getApplicationContext()).getAbsolutePath())
                        FileUtil.getTempDirPath(getApplicationContext()))//定义路径为：sdcard/[app name]/
                .setLogSaver(new LogRecorder(context))
                .setLogDebugModel(false)
                .init(getApplicationContext());
    }

    private void loadLocalProxyDomain() {
        if (cache.getCache("proxyDomain") == "") {
            AssetManager assetManager = getAssets();
            try {
                InputStreamReader inputStreamReader = new InputStreamReader(assetManager.open("defultProxyDomain"), "UTF-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line = bufferedReader.readLine();
                cache.saveCache("proxyDomain", line);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        System.gc();
    }
}
